﻿using System.Net;
using System.Text;
using Maple.Weixin.MP.Entities;
using Newtonsoft.Json;

namespace Maple.Weixin.MP.Helpers
{
    public static class HttpHelper
    {
        public static string Get(string url, Encoding encoding = null) {
            var client = new WebClient {Encoding = encoding ?? Encoding.UTF8};
            var returnText = client.DownloadString(url);
            return returnText;
        }

        public static string Post(string url, string json, Encoding encoding = null) {
            var client = new WebClient {Encoding = encoding ?? Encoding.UTF8};
            return client.UploadString(url, json);
        }

        public static string UploadMedia(string accessToken, UploadMediaType mediaType, string fileName,
                                         Encoding encoding = null) {
            var client = new WebClient {Encoding = encoding ?? Encoding.UTF8};
            var url = WeixinHelper.GetUploadMediaUrl(accessToken, mediaType);
            var bytes = client.UploadFile(url, fileName);
            var text = Encoding.UTF8.GetString(bytes);
            return text;
        }

        public static string UploadMedia(string accessToken, UploadMediaType mediaType, string fileName,
                                         out string mediaId, Encoding encoding = null) {
            mediaId = "";
            var text = UploadMedia(accessToken, mediaType, fileName, encoding);
            if (!text.Contains("errorcode")) {
                var obj = JsonConvert.DeserializeAnonymousType(text,
                                                               new {type = "", media_id = "", created_at = ""});
                mediaId = obj.media_id;
            }
            return text;
        }

        public static void DownloadMedia(string accessToken, string mediaId, string fileName, Encoding encoding = null) {
            var client = new WebClient { Encoding = encoding ?? Encoding.UTF8 };
            var url = WeixinHelper.GetDownloadMediaUrl(accessToken, mediaId);
            client.DownloadFile(url, fileName);
        }
    }
}
